import { Component, FunctionalVue } from "@some21/vue-class-decorator";

// 统计数组的连续字符数
function countConsecutiveCharacters(arr: any[]) {
  const result = [];
  arr.forEach(item => {
    if (result.length === 0) {
      result.push([item, 1]);
    } else {
      const last = result[result.length - 1];
      if (last[0] === item) {
        last[1] = last[1] + 1;
      } else {
        result.push([item, 1]);
      }
    }
  });

  return result;
}

@Component({
  name: "Ju-HighlightKey",
})
export default class extends FunctionalVue {
  render(h, context) {
    let { value, keys, color } = context.props;
    // 识别 splitKey 参数，默认为 false, 当splitKey 存在时，且不为false ，则为true
    const splitKey = typeof context.props.splitKey !== "undefined" && context.props.splitKey !== false;
    if (!value) {
      return;
    } else if (!keys || typeof value !== "string") {
      return [value];
    }
    // 判断如果颜色不存在，则使用默认主题颜色
    if (!color) {
      color = "var(--theme-danger)";
    }
    // 存储最终返回的Vnodes
    const resultVNodes = [];
    // 判断 value 中是否存在关键字 keys，若存在，则将关键字高亮显示

    keys = keys.toUpperCase();

    if (splitKey) {
      const splitKeys = keys.toUpperCase().split("");

      let currentKeyIndex = 0;
      const checkValues = value
        .toUpperCase()
        .split("")
        .map(m => {
          const isChecked = m === splitKeys[currentKeyIndex];
          if (isChecked) {
            currentKeyIndex++;
          }
          return isChecked;
        });

      // const checkValues = value
      //   .toUpperCase()
      //   .split("")
      //   .map(m => keys.toUpperCase().includes(m));

      // 统计 checkValues 中每个值出现的次数
      const checkValuesConsecutives = countConsecutiveCharacters(checkValues);
      checkValuesConsecutives.forEach(item => {
        if (item[0]) {
          resultVNodes.push(h("span", { style: { color } }, value.substring(0, item[1])));
        } else {
          resultVNodes.push(value.substring(0, item[1]));
        }
        value = value.substring(item[1]);
      });
    } else {
      while (value.toUpperCase().indexOf(keys) >= 0) {
        const keyIndex = value.toUpperCase().indexOf(keys);
        const partValue = value.substring(0, keyIndex);
        const keyValue = value.substring(keyIndex, keyIndex + keys.length);
        value = value.substring(keyIndex + keys.length);
        resultVNodes.push(partValue);
        resultVNodes.push(h("span", { style: { color } }, keyValue));
      }
    }
    if (value) {
      resultVNodes.push(value);
    }

    return resultVNodes;
  }
}
